<template>
  <!-- <TagsView/> -->
  <!-- 年度考核题库 题库制作-->
  <div class="container project">
    <div class="tree" v-loading="data.loading">
      <catalog :tree-data="data.tableTreeData.questionList" :default-expanded-keys="data.defaultExpandedKeys"
        @on-search="orgSearch" :searchFlag="false" />
    </div>

    <div class="data" v-loading="data.loading">
      <el-row class="header">
        <el-col :span="6">
        </el-col>
        <el-col :span="18" align="right">
          <el-button type="primary" @click="back">返回</el-button>
          <el-button class="ordinary" @click="preview()" v-if="route.query.type != 'repeat'">自评预览</el-button>
          <el-button type="primary" @click="save()" v-if="route.query.type != 'look'">保存</el-button>
        </el-col>
      </el-row>
      <div class="banner" v-if="Object.keys(bannerData).length != 0"
        :style="route.query.type != 'self' ? 'background:rgb(204 204 204 / 35%)' : ''">
        <h3>{{ bannerData.number }} {{ bannerData.title }} {{ `(` + bannerData.questionType_text + `)` }}</h3>
        <p class="scoreMethod">[计分方法]：{{ bannerData.scoreMethod }}</p>
        <!-- 题目 -->
        <div class="topic">
          <div class="left">
            <p class="t">自评输入：</p>
            <ul>
              <li v-for="item in bannerData.questionItemList" :key="item.id">
                <!-- 单选 -->
                <el-radio-group v-model="bannerData.checkRadio" v-if="bannerData.questionType == '1'"
                  @change="changeRadio('self')" :disabled="route.query.type != 'self'">
                  <el-radio :label="item.id">{{ item.number }} {{ item.title }} （{{ item.itemScore }}）</el-radio>
                </el-radio-group>
                <!-- 多选 -->
                <el-checkbox-group v-model="bannerData.checkBox" v-if="bannerData.questionType == '2'"
                  @change="changeCheck('self')" :disabled="route.query.type != 'self'">
                  <el-checkbox :label="item.id">{{ item.number }} {{ item.title }} （{{ item.itemScore }}）</el-checkbox>
                </el-checkbox-group>
                <div v-if="item.title.includes('其它') && item.answerItem.selfCheckedFlag">
                  <el-input v-model="data.tableTreeData.remark"  style="width: 280px" :rows="2" type="textarea"
                    placeholder="请输入" />
                </div>
                <!-- 填空 -->
                <p v-if="bannerData.questionType == '3'">
                  <span>{{ item.number }} {{ item.title }}</span>
                  <el-input v-model="item.answerItem.selfInput" :disabled="route.query.type != 'self'"></el-input>
                </p>

              </li>
            </ul>
          </div>
          <div class="right" v-if="route.query.type == 'repeat' || route.query.type == 'look'">
            <p class="t">复评输入：</p>
            <ul>
              <li v-for="item in bannerData.questionItemList" :key="item.id">
                <!-- 单选 -->
                <el-radio-group v-model="bannerData.checkRadioRepeat" v-if="bannerData.questionType == '1'"
                  @change="changeRadio('repeat')" :disabled="route.query.type == 'look'">
                  <el-radio :label="item.id">{{ item.number }} {{ item.title }} （{{ item.itemScore }}）</el-radio>
                </el-radio-group>
                <!-- 多选 -->
                <el-checkbox-group v-model="bannerData.checkBoxRepeat" v-if="bannerData.questionType == '2'"
                  @change="changeCheck('repeat')" :disabled="route.query.type == 'look'">
                  <el-checkbox :label="item.id">{{ item.number }} {{ item.title }} （{{ item.itemScore }}）

                  </el-checkbox>
                </el-checkbox-group>

                <div v-if="item.title.includes('其它') && item.answerItem.selfCheckedFlag">
                  <el-input  v-model="item.remark" style="width: 280px" :rows="2" type="textarea"
                    placeholder="请输入信息" />
                </div>

                <!-- 填空 -->
                <div v-if="bannerData.questionType == '3'">
                  <span>{{ item.number }} {{ item.title }}</span>
                  <div style="display: flex;">
                    <el-input v-model="item.answerItem.repeatInput" :disabled="route.query.type == 'look'"></el-input>
                    <span style="width: 100px;text-align: center;line-height: 30px;">得分：</span>
                    <!--                    //之前的取值-->
                    <!--                    <el-input v-model="item.itemScore" style="width: 100px;" :disabled="route.query.type == 'look'"></el-input>-->
                    <el-input v-model="item.answerItem.repeatScore" style="width: 100px;"
                      :disabled="route.query.type == 'look'"></el-input>
                  </div>
                </div>
              </li>
            </ul>
            <p>
              <span class="t" style="line-height: 30px;">复评意见：</span>
              <el-input v-if="bannerData.answer" v-model="bannerData.answer.repeatSuggest" style="width: 100%;"
                :disabled="route.query.type == 'look'"></el-input>
            </p>
          </div>
        </div>

        <div class="file_box">
          <p class="t">上传附件： (单个附件大小限定200M内。上传成功后须点保存按钮。)</p>
          <el-upload class="upload-demo" :headers="headers" :show-file-list="false"
            :file-list="bannerData.answerAttachmentList" action="/fastDfs/file/upload" multiple
            :before-upload="beforeAvatarUpload" :on-preview="handlePreview" :on-remove="handleRemove"
            :before-remove="beforeRemove" :limit="3" :on-exceed="handleExceed" :on-success="handleSuccess"
            :on-change="handleChange">
            <el-button type="primary" :disabled="route.query.type != 'self'">上传文件</el-button>
            <template #tip>
              <div class="el-upload__tip"></div>
            </template>
          </el-upload>

          <platformFiles :filesTypeFlag="false" :isExamine="true" :isDisabled="route.query.type == 'self'"
            :files="bannerData.answerAttachmentList" @filesParams="filesParams"></platformFiles>
        </div>

      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import platformFiles from '@/views/examineManage/platformFiles/platformFiles.vue';
import type { UploadProps, UploadUserFile } from 'element-plus';
import { ElMessage } from "element-plus";
import { reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import Catalog from '../../../project/components/Catalog/index.vue';
import * as api from "../../api/eachUnit";

const searchFrom = reactive({
  //查询
  companyName: "",
  size: 10,
  current: 1,
});
const route = useRoute();
const router = useRouter();
const data = reactive({
  tableTreeData: {} as any,
  defaultExpandedKeys: [],
  bannerData: {} as any,
  loading: false,
  fatherIndex: 0,//当前点击的tree中数组的下标是哪个
})
let bannerData = ref({} as any)
//返回
const back = () => {
  router.go(-1)
}
//获取数据
const getData = () => {
  api.getFaNumber({ id: route.query.bankId }).then(res => {
    console.log('获取数据', res.data.data.questionList);
    data.tableTreeData = JSON.parse(JSON.stringify(res.data.data))
    data.defaultExpandedKeys = (data.tableTreeData.questionList as any).map((item) => item.id)
  })
}
//tree左侧事件
const orgSearch = (val) => {
  if (val.classType == '3' || val.classType == '4') {
    //自评
    // bannerData.value = val
    bannerData.value = Object.assign({}, val)
    bannerData.value.checkRadio = ''  //加一个单选选中的结果
    bannerData.value.checkBox = []  //加一个多选选中的结果
    bannerData.value.checkRadioRepeat = ''  //加一个单选选中的结果
    bannerData.value.checkBoxRepeat = []  //加一个多选选中的结果
    //加一个文件数据---------
    bannerData.value.fileList = []
    bannerData.value.answerAttachmentList.forEach(e => {
      // bannerData.value.fileList.push({name:e.fileName,fileName:e.fileName,url:e.path})
    })
    //为每个题目加上放答案对象
    if (bannerData.value.questionItemList.length > 0) {
      bannerData.value.questionItemList.forEach(e => {
        // console.log('e',e);
        let answerItem = reactive({
          questionNumber: e.number,//A B C
          selfCheckedFlag: false,
          selfInput: null,
          selfInputTitle: null,
          selfScore: e.itemScore,
          repeatCheckedFlag: false,
          repeatInput: null,
          repeatScore: e.itemScore,
          remark: null,
          otherFlag: false,
        })
        if (!e.answerItem) {
          Reflect.set(e, 'answerItem', answerItem)
        }
        //自评 --单选结果回显
        if (e.answerItem && e.answerItem.selfCheckedFlag == true) {
          bannerData.value.checkRadio = e.id
          bannerData.value.checkBox.push(e.id)
        }
        //复评 --单选结果回显
        if (e.answerItem && e.answerItem.repeatCheckedFlag == true) {
          bannerData.value.checkRadioRepeat = e.id
          bannerData.value.checkBoxRepeat.push(e.id)
        }
      })
    }
    console.log('左侧事件', bannerData.value);

    //获取当前tree点击的父级下标 为了附件-----
    let ind = bannerData.value.number.substring(0, bannerData.value.number.indexOf('.'))
    data.fatherIndex = data.tableTreeData.questionList.findIndex(e => {
      return e.number === ind
    })

  } else {
    bannerData.value = {}
  }
}
// 自评radio change
const changeRadio = (type) => {
  console.log('type', type);
  bannerData.value.questionItemList.forEach(e => {
    if (type == 'self') {
      if (bannerData.value.checkRadio === e.id) {
        e.answerItem.selfCheckedFlag = true

      } else {
        e.answerItem.selfCheckedFlag = false
      }
    } else {
      if (bannerData.value.checkRadioRepeat === e.id) {
        e.answerItem.repeatCheckedFlag = true
      } else {
        e.answerItem.repeatCheckedFlag = false
      }
    }
  })
}
// 自评checkout change
const changeCheck = (type) => {
  // console.log('val',bannerData.value.checkBox);
  bannerData.value.questionItemList.forEach(e => {
    if (type == 'self') {
      
      if (bannerData.value.checkBox.indexOf(e.id) > -1) {
        if(e.title.includes("其它")){
          
          
          e.answerItem.otherFlag = true
        }
        
        e.answerItem.selfCheckedFlag = true
      } else {

        if(e.title.includes("其它")){
        
          e.answerItem.otherFlag = false
        }
        
        e.answerItem.selfCheckedFlag = false
      }
    } else {
      
      // console.log('changeCheck',bannerData.value.checkBoxRepeat,'====',e.id,'=====',bannerData.value.checkBoxRepeat.indexOf(e.id));
      if (bannerData.value.checkBoxRepeat.indexOf(e.id) > -1) {
        e.answerItem.repeatCheckedFlag = true
      } else {
        e.answerItem.repeatCheckedFlag = false
      }
    }
  })

}
//自评预览
const preview = () => {
  router.push({
    path: "/examineManage/digitalExamine/selfPreview",
    query: {
      bankId: route.query.bankId,
    },
  });
}
// 保   存
const save = () => {
  console.log('保   存', bannerData.value, data.tableTreeData);

  data.loading = true
  if (route.query.type == 'repeat') {
    data.tableTreeData.repeatFlag = true
  }
  api.saveExamine(data.tableTreeData).then(res => {
    // console.log('res',res);
    if (res.data.code == 200) {
      ElMessage.success('保存成功')
      data.loading = false
    }
  })
}

watch(bannerData, (newValue, oldValue) => {
  // console.log('newValue',newValue,data.tableTreeData,);
}, { deep: true });
//--------------------------附件相关----------------------------
//上传附件
const filesParams = (params) => {
  // data.files = params
  params.value.forEach(e => {
    e.path = e.filePath
  })
  console.log('上传附件params', params.value);
  let list = params.value
  bannerData.value.answerAttachmentList = list
  if (bannerData.value.number == data.tableTreeData.questionList[data.fatherIndex].number) {
    data.tableTreeData.questionList[data.fatherIndex].answerAttachmentList = list
  } else {
    data.tableTreeData.questionList[data.fatherIndex].children.forEach(e => {
      if (e.number == bannerData.value.number) {
        console.log('找到了1', e.id);
        e.answerAttachmentList = list
        return false
      } else {
        e.children.forEach(j => {
          if (j.number == bannerData.value.number) {
            console.log('找到了2', j.id);
            j.answerAttachmentList = list
            return false
          }
        })
      }
    })
  }
}
const cookie = () => localStorage.getItem('token')
const headers = { Authorization: 'Bearer ' + cookie() }
const fileList = ref<typeof UploadUserFile[]>([])
const loading = ref(false)
const beforeAvatarUpload: typeof UploadProps['beforeUpload'] = (rawFile) => {
  loading.value = true
}
const handlePreview: typeof UploadProps['onPreview'] = (uploadFile) => {
  console.log('handlePreview', uploadFile)
}
const handleRemove: typeof UploadProps['onRemove'] = (file, fileList) => {
  // fileList.value.splice(fileList.value.indexOf(file), 1)

}
const beforeRemove: typeof UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  console.log('beforeRemove')
}
const handleExceed: typeof UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  )
}
const handleSuccess: typeof UploadProps['onSuccess'] = (res, uploadFile, fileList) => {
  console.log('uploadFile', uploadFile);
  let list = [] as any
  fileList.forEach(e => {
    console.log('e.response', e);
    list.push({
      name: e.name,
      fileName: e.name,
      fileId: e.uid,
      fileType: uploadFile.response.data.type,
      path: e.response ? e.response.data.path : e.url,
      // response: e.response,
    })
    console.log('list', list);
  })


  if (res.code == 200) {
    ElMessage.success('上传成功')
    bannerData.value.answerAttachmentList = list
    if (bannerData.value.number == data.tableTreeData.questionList[data.fatherIndex].number) {
      data.tableTreeData.questionList[data.fatherIndex].answerAttachmentList = list
    } else {
      data.tableTreeData.questionList[data.fatherIndex].children.forEach(e => {
        if (e.number == bannerData.value.number) {
          console.log('找到了1', e.id);
          console.log('找到了1', list);
          e.answerAttachmentList = list
          return false
        } else {
          e.children.forEach(j => {
            if (j.number == bannerData.value.number) {
              console.log('找到了2', j.id);
              console.log('找到了2', list);
              j.answerAttachmentList = list
              return false
            }
          })
        }
      })
    }
    list = []
    // const deepCloneData = [_clone(data.tableTreeData.questionList[data.fatherIndex])]
    // const resultData = changeTreePostionData(data.tableTreeData.questionList,data.fatherIndex, bannerData.value.id, fileList)
    // data.tableTreeData.questionList[data.fatherIndex] = resultData
    // console.log('resultData',resultData);
    loading.value = false
  } else {
    ElMessage.error('上传失败')
  }
}
const handleChange: typeof UploadProps['onChange'] = (uploadFile, fileList) => {
  //限制上传文件大小
  if (!uploadFile) return
  const isLt2M = uploadFile.size / 1024 / 1024 < 200
  if (!isLt2M) {
    ElMessage.warning(`上传文件大小不能超过 200MB!`)
    return false
  }
}

getData()
</script>

<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
  overflow-y: auto;
}

// :deep(.el-dialog__body) {
//   padding: 0 !important
// }
:deep(.el-dialog__body) {
  padding: 0;
}

.dialogCloseBtn {
  position: absolute;
  top: 20px;
  right: 20px;
}

// .el-col {
//   line-height: 60px;
// }

.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

:deep(.demo-tabs > .el-tabs__content) {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

:deep(.demo-tabs > .el-tabs__content::-webkit-scrollbar) {
  display: none;
  /* Chrome Safari */
}

.demo-form-inline .el-form-item {
  width: 30%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

.project {
  display: flex;

  .tree {
    width: 20%;
  }

  .data {
    width: 80%;
  }
}

.banner {
  min-height: 360px;
  overflow-y: auto;
  border: 1px solid #e6ebf5;
  margin-top: 20px;
  padding: 0 10px;

  .scoreMethod {
    font-size: 18px;
    padding: 10px;
    border: 1px solid #e6ebf5
  }

  ;

  .t {
    font-weight: bold;
  }

  .topic {
    display: flex;
    justify-content: space-between;
    padding: 0 10px;

    ul {
      margin: 0;
      padding: 0;

      li {
        list-style: none;
        line-height: 40px;
      }
    }

    .left {
      width: 40%;
      padding: 0 20px;
    }

    .right {
      width: 50%;
      padding: 0 20px;
      background: #fff;
    }
  }

  .file_box {
    padding: 0 10px;
    margin-top: 100px;
    margin-bottom: 20px;
  }
}
</style>
